package cn.cnhis.online.mymodule.mybasenet;

import java.io.IOException;

import cn.cnhis.online.mymodule.BaseApplication;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by wuzhc on 2018/2/5.
 * 缓存过滤
 */
public class CachingControlInterceptor {
    private static final int TIMEOUT_CONNECT = 10; // 10秒
    private static final int TIMEOUT_DISCONNECT = 60 * 60 * 2; // 2小时

    public static final Interceptor REWRITE_RESPONSE_INTERCEPTOR = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            //获取retrofit @headers里面的参数 参数可以自己定义     自定义的是cache 跟@headers里面对应就可以了
            String cache = chain.request().header("cache");
            Response originalResponse = chain.proceed(chain.request());
            String cacheControl = originalResponse.header("Cache-Control");
            // 如果cacheControl为空 就让他TIMEOUT_CONNECT秒的缓存 这里的cacheControl是服务器返回的
            if (cacheControl == null) {
                //如果cache没值，缓存时间为TIMEOUT_CONNECT，有的话就为cache的值
                if (cache == null || "".equals(cache)) {
                    cache = TIMEOUT_CONNECT + "";
                }
                originalResponse = originalResponse.newBuilder()
                        .removeHeader("Pragma")
                        .addHeader("Cache-Control", "public, max-age=" + cache)
                        .build();
                return originalResponse;
            } else {
                return originalResponse;
            }
        }
    };

    public static final Interceptor REWRITE_RESPONSE_INTERCEPTOR_OFFLINE = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            // 离线的时候为TIMEOUT_DISCONNECT的缓存
//            if (!NetworkUtil.isNetAvailable(BaseApplication.getINSTANCE())) {
//                request = request.newBuilder()
//                        .removeHeader("Pragma")
//                        .addHeader("Cache-Control", "public, only-if-cached, max-stale=" + TIMEOUT_DISCONNECT)
//                        .build();
//            }
            return chain.proceed(request);
        }
    };
}
